package cn.sc.collection.base;

import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;

/**
 * @ClassName CacheObject
 * @Author 谢卓才
 * @Description 存储的中介对象
 * @Date 2022/11/13 9:17
 */
public class CacheObject<V> implements Serializable {
    /**
     * 保持的数据
     */
    protected V cachedObject;
    /**
     * 记录保持时间
     */
    long lastAccess;
    /**
     * 使用次数
     */
    long accessCount;
    /**
     * 保持的数据
     */
    long ttl;

    /**
     * 数据class类型
     */
    Class<V> dataType;

    public CacheObject( V object, long ttl, Class<V> cla) {
        this.cachedObject = object;
        this.ttl = ttl;
        this.lastAccess = System.currentTimeMillis();
        this.dataType = cla;
    }

    public CacheObject( V object, long ttl, long lastAccess, long accessCount, Class<V> cla) {
        this.cachedObject = object;
        this.ttl = ttl;
        this.lastAccess = lastAccess;
        this.accessCount = accessCount;
        this.dataType = cla;
    }

    /**
     * 是否过期，true:表示过期。
     */
    public boolean isExpired() {
        if (this.ttl == 0L) {
            return false;
        } else {
            return this.lastAccess + this.ttl < System.currentTimeMillis();
        }
    }

    public String changeString(){
        StringBuilder ping = new StringBuilder();
        ping.append(this.cachedObject);
        ping.append(",");
        ping.append(ttl);
        ping.append(",");
        ping.append(lastAccess);
        ping.append(",");
        ping.append(accessCount);

        return ping.toString();
    }

    public static CacheObject<String> stringChange(String data){
        String[] split = data.split(",");
        if(split.length != 4){
            return null;
        }
        CacheObject<String> dataObject = new CacheObject<>(split[0], Long.valueOf(split[1]), Long.valueOf(split[2]), Long.valueOf(split[3]), String.class);
        return dataObject;
    }

    /**
     * 获取value
     */
    public V getObject() {
        return getObject(false);
    }

    /**
     * 获取value,刷新时间
     */
    public V getObject(boolean refresh) {
        if (refresh){
            this.lastAccess = System.currentTimeMillis();
        }
        ++this.accessCount;
        return this.cachedObject;
    }

    /**
     * 获取value,刷新时间
     */
    public void setObject(V data) {
        this.cachedObject = data;
    }

    /**
     * accessCount增加值
     * @param count 值
     */
    public void incrAccessCount(long count) {
        this.accessCount += count;
    }

    /**
     * 获取保持数据的class类型
     * @return
     */
    public Class<V> getDataType() {
        return dataType;
    }

}
